using System;
using System.Linq.Expressions;

namespace DotNetCRM.Core.ExtensionMethods
{
    public static class ExpressionExtensions
    {
        public static string MemberName<T, U>(this Expression<Func<T, U>> expression)
        {
            return GetMemberName(expression);
        }

        private static string GetMemberName<T, U>(Expression<Func<T, U>> expression)
        {
            MemberExpression memberExpression = expression.Body as MemberExpression;
            if(memberExpression == null)
            {
                UnaryExpression unaryExpression = expression.Body as UnaryExpression;
                if(unaryExpression != null)
                {
                    memberExpression = unaryExpression.Operand as MemberExpression;
                }
            }
            if(memberExpression != null)
            {
                return memberExpression.Member.Name;
            }
            throw new ApplicationException("Member Name not found");
        }
    }
}